package com.loma.common.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.JsonParseException
import com.loma.common.model.http.ApiException
import com.loma.common.utils.ext.log
import kotlinx.coroutines.*

import java.net.ConnectException
import java.net.SocketTimeoutException

typealias Block<T> = suspend () -> T
typealias Error = suspend (e: Exception) -> Unit
typealias Cancel = suspend (e: Exception) -> Unit

/**
 * Created by xiaojianjun on 2019-09-20.
 */
open class ViewModelBase : ViewModel() {
    val exception: MutableLiveData<Exception> = MutableLiveData()
    val showProgress = MutableLiveData<Boolean>()
    val submitResult = MutableLiveData<Boolean>()

    /**
     * 创建并执行协程
     * @param block 协程中执行
     * @param error 错误时执行
     * @return Job
     */
    protected fun launch(block: Block<Unit>, error: Error? = null, cancel: Cancel? = null): Job {
        return viewModelScope.launch {
            try {
                block.invoke()
            } catch (e: Exception) {
                when (e) {
                    is CancellationException -> {
                        showProgress.value = false
                        cancel?.invoke(e)
                    }
                    else -> {
                        e.log()
                        onError(e)
                        error?.invoke(e)
                    }
                }
            }
        }
    }




    /**
     * 统一处理错误
     * @param e 异常
     */
    private fun onError(e: Exception) {
        when (e) {
            is ApiException -> {
                when (e.code) {

                    -1 -> {
                        // 其他api错误
                    }
                    -401 -> {
                        // 其他api错误


                    }
                    else -> {
                        // 其他错误

                    }
                }
            }



            is ConnectException -> {
                e.message.let { "连接失败" }
                // 连接失败
            }
            is SocketTimeoutException -> {
                // 请求超时
                e.message.let { "请求超时" }
            }
            is JsonParseException -> {
                e.message.let { "数据解析错误" }
                // 数据解析错误
            }
            else -> {
                // 其他错误
                e.message.let { "其他错误" }
            }


        }

        e.message?.log()
        exception.value = e
        showProgress.value = false
        submitResult.value = false
    }





}




